#include "WrcProxyLocal.h"

namespace varayoc
{
namespace wrcproxy
{
namespace runnable
{

WrcProxyLocal::WrcProxyLocal()
{
}

Void WrcProxyLocal::initSocket()
{
   m_udpServer = new QUdpSocket(0);
   QHostAddress   ipAddress   = QHostAddress::LocalHost;
   Int            port        = 7755;

   m_udpServer->bind(ipAddress, port);

//   connect(m_udpServer, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));
}

void WrcProxyLocal::readPendingDatagrams()
{
   std::cout << "---" << std::endl;
   while (m_udpServer->hasPendingDatagrams())
   {
      QByteArray datagram;
      datagram.resize(m_udpServer->pendingDatagramSize());
      QHostAddress sender;
      quint16 senderPort;
      m_udpServer->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);

      processTheDatagram(datagram);

//      m_udpServer->writeDatagram(datagram.data(), datagram.size(), sender, senderPort);
   }
}

Void WrcProxyLocal::processTheDatagram(QByteArray datagram)
{
   // validaciones de tramas
   qDebug() << "datagram : " << datagram.data();
}

WrcProxyLocal_ptr   WrcProxyLocal::create()
{
   return WrcProxyLocal_ptr(new WrcProxyLocal());
}

WrcProxyLocal::~WrcProxyLocal()
{
}

Bool WrcProxyLocal::startWrcProxyLocal()
{
   Bool ret = False;
   initSocket();

//   QTextStream qout(stdout);

//   QUdpSocket *udpSocket = new QUdpSocket(0);
//   udpSocket->bind(3838, QUdpSocket::ShareAddress);
while(1)
   {
   //1.
   //2.
   //if while (m_udpServer->waitForReadyRead(-1)) {
      // RMS
      // 1.
   sleep(1);
   std::cout << "llamada 1" << std::endl;
      // 2.
      while(m_udpServer->hasPendingDatagrams()) {
         QByteArray datagram;
         datagram.resize(m_udpServer->pendingDatagramSize());
         QHostAddress sender;
         quint16 senderPort;

         m_udpServer->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
         processTheDatagram(datagram);
         m_udpServer->writeDatagram(datagram.data(), datagram.size(), sender, senderPort);
//         qout << "datagram received from " << sender.toString() << "data : " << datagram.data() << endl;
      }
   //}
}
   return ret;
}
Void WrcProxyLocal::stopWrcProxyLocal()
{
}

}}}
